﻿namespace USSDRunner.ViewModels
{
    using System.Linq;
    
    /// <summary>
    /// Represents base view model for USSD message body or parameter.
    /// </summary>
    public abstract class MessageItemViewModelBase : NotifyPropertyChangedBase
    {
        /// <summary>
        /// The character, used as start character of USSD message or parameter.
        /// </summary>
        public const char Asterisk = '*';

        /// <summary>
        /// The character, used as USSD message end character.
        /// </summary>
        private const char Hash = '#';

        private string text;

        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        /// <value>
        /// The text.
        /// </value>
        public string Text
        {
            get
            {
                return text;
            }

            set
            {
                if (text != value)
                {
                    text = value;
                    OnPropertyChanged("Text");

                    WriteTextToIsolatedStorage();
                }
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is valid.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is valid; otherwise, <c>false</c>.
        /// </value>
        public bool IsValid
        {
            get
            {
                return !string.IsNullOrEmpty(Text) && Text.All(ch => IsCharDigit(ch) || ch == Asterisk || ch == Hash);
            }
        }

        /// <summary>
        /// Gets the text key.
        /// </summary>
        protected abstract string TextKey { get; }

        /// <summary>
        /// Loads the text from isolated storage.
        /// </summary>
        public void LoadTextFromIsolatedStorage()
        {
            Text = MessageViewModel.ReadFromIsolatedStorage(TextKey);
        }

        /// <summary>
        /// Writes the text to isolated storage.
        /// </summary>
        private void WriteTextToIsolatedStorage()
        {
            MessageViewModel.WriteToIsolatedStorage(TextKey, Text);
        }

        /// <summary>
        /// Determines whether the specified char <paramref name="ch"/> is digit.
        /// </summary>
        /// <param name="ch">The char.</param>
        /// <returns>
        ///   <c>true</c> if the specified char <paramref name="ch"/> is digit; otherwise, <c>false</c>.
        /// </returns>
        private static bool IsCharDigit(char ch)
        {
            return "0123456789".Contains(ch);
        }
    }
}